// ConstantArray.cpp
#include "ConstantArray.h"
#include "PointerType.h"
#include <sstream>

ConstantArray::ConstantArray(PointerType* type, const std::vector<Value*>& values)
    : Constant(type), values(values) {}

std::string ConstantArray::toString() const {
    std::ostringstream oss;
    auto* arrType = static_cast<PointerType*>(type);
    const Type* elemType = arrType->getElementType();
    size_t elemCount = arrType->getSize() / elemType->getSize();

    oss << "[";

    if (elemType->isPointerType()) {
        // 嵌套数组，递归输出每一项并加上类型前缀
        auto* subPointerType = dynamic_cast<PointerType*>(const_cast<Type*>(elemType));
        if (!subPointerType) {
            // 类型转换失败，返回错误信息或抛出异常
            oss << "<Invalid PointerType>";
        } else {
            size_t subArraySize = subPointerType->getSize() / subPointerType->getRootType()->getSize();

            for (size_t i = 0; i < elemCount; ++i) {
                if (i > 0) oss << ", ";

                // 构造子数组的值切片
                std::vector<Value*> subValues(
                    values.begin() + i * subArraySize,
                    values.begin() + (i + 1) * subArraySize
                );

                // 递归构造子 ConstantArray 并调用其 toString
                ConstantArray subArray(subPointerType, subValues);
                oss << subPointerType->toString() << " " << subArray.toString();  // 显式写类型
            }
        }
    } else {
        for (size_t i = 0; i < values.size(); ++i) {
            if (i > 0) oss << ", ";
            oss << elemType->toString() << " " << values[i]->getIRName();
        }
    }

    oss << "]";
    return oss.str();
}
